<template>
  <div class="inspection-form">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <h2>{{ isEdit ? '编辑检测报告' : '新增检测报告' }}</h2>
      </div>
      <div class="header-right">
        <el-button @click="goBack">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </div>
    </div>

    <div class="form-content">
      <el-form
        ref="inspectionForm"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="inspection-form-container"
      >
        <!-- 基本信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="检测编号" prop="inspectionCode">
                <el-input
                  v-model="formData.inspectionCode"
                  placeholder="请输入检测编号"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检测类型" prop="inspectionType">
                <el-select
                  v-model="formData.inspectionType"
                  placeholder="请选择检测类型"
                  style="width: 100%"
                  clearable
                >
                  <el-option label="常规检测" value="routine" />
                  <el-option label="专项检测" value="special" />
                  <el-option label="复检" value="recheck" />
                  <el-option label="抽检" value="sampling" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品" prop="productId">
                <el-select
                  v-model="formData.productId"
                  placeholder="请选择商品"
                  style="width: 100%"
                  filterable
                  @change="handleProductChange"
                >
                  <el-option
                    v-for="product in products"
                    :key="product.id"
                    :label="`${product.name} (${product.code})`"
                    :value="product.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生产批次" prop="batchNumber">
                <el-input
                  v-model="formData.batchNumber"
                  placeholder="请输入生产批次"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierId">
                <el-select
                  v-model="formData.supplierId"
                  placeholder="请选择供应商"
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="supplier in suppliers"
                    :key="supplier.id"
                    :label="supplier.name"
                    :value="supplier.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检测日期" prop="inspectionDate">
                <el-date-picker
                  v-model="formData.inspectionDate"
                  type="date"
                  placeholder="选择检测日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="检测员" prop="inspector">
                <el-input
                  v-model="formData.inspector"
                  placeholder="请输入检测员姓名"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检测地点" prop="inspectionLocation">
                <el-input
                  v-model="formData.inspectionLocation"
                  placeholder="请输入检测地点"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 检测项目 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>检测项目</span>
              <el-button type="primary" size="small" @click="addTestItem">
                <el-icon><Plus /></el-icon>
                添加检测项目
              </el-button>
            </div>
          </template>
          
          <div v-for="(item, index) in formData.testItems" :key="index" class="test-item">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item :label="index === 0 ? '检测项目' : ''" :prop="`testItems.${index}.testItem`">
                  <el-select
                    v-model="item.testItem"
                    placeholder="选择检测项目"
                    style="width: 100%"
                    clearable
                  >
                    <el-option label="农药残留" value="农药残留" />
                    <el-option label="重金属" value="重金属" />
                    <el-option label="微生物" value="微生物" />
                    <el-option label="添加剂" value="添加剂" />
                    <el-option label="外观检查" value="外观检查" />
                    <el-option label="理化指标" value="理化指标" />
                    <el-option label="营养成分" value="营养成分" />
                    <el-option label="其他" value="其他" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item :label="index === 0 ? '检测方法' : ''" :prop="`testItems.${index}.testMethod`">
                  <el-input
                    v-model="item.testMethod"
                    placeholder="检测方法"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item :label="index === 0 ? '检测值' : ''" :prop="`testItems.${index}.testValue`">
                  <el-input
                    v-model="item.testValue"
                    placeholder="检测值"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item :label="index === 0 ? '标准值' : ''" :prop="`testItems.${index}.standard`">
                  <el-input
                    v-model="item.standard"
                    placeholder="标准值"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item :label="index === 0 ? '单位' : ''" :prop="`testItems.${index}.unit`">
                  <el-input
                    v-model="item.unit"
                    placeholder="单位"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item :label="index === 0 ? '检测结果' : ''" :prop="`testItems.${index}.testResult`">
                  <el-select
                    v-model="item.testResult"
                    placeholder="结果"
                    style="width: 100%"
                  >
                    <el-option label="合格" value="合格" />
                    <el-option label="不合格" value="不合格" />
                    <el-option label="待定" value="待定" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item :label="index === 0 ? '操作' : ''">
                  <el-button type="danger" size="small" @click="removeTestItem(index)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-card>

        <!-- 检测结果汇总 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>检测结果汇总</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="检测项目总数">
                <el-input-number
                  v-model="formData.totalTests"
                  :min="0"
                  style="width: 100%"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合格项目数">
                <el-input-number
                  v-model="formData.passedTests"
                  :min="0"
                  style="width: 100%"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="不合格项目数">
                <el-input-number
                  v-model="formData.failedTests"
                  :min="0"
                  style="width: 100%"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合格率">
                <el-input
                  v-model="formData.passRate"
                  placeholder="自动计算"
                  disabled
                  style="width: 100%"
                >
                  <template #append>%</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="综合判定" prop="overallResult">
                <el-radio-group v-model="formData.overallResult">
                  <el-radio label="合格">合格</el-radio>
                  <el-radio label="不合格">不合格</el-radio>
                  <el-radio label="待定">待定</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检测状态" prop="status">
                <el-select
                  v-model="formData.status"
                  placeholder="请选择检测状态"
                  style="width: 100%"
                >
                  <el-option label="进行中" value="processing" />
                  <el-option label="已完成" value="completed" />
                  <el-option label="已审核" value="reviewed" />
                  <el-option label="已发布" value="published" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 检测结论 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>检测结论</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="检测结论" prop="conclusion">
                <el-input
                  v-model="formData.conclusion"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入检测结论"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="处理建议" prop="recommendations">
                <el-input
                  v-model="formData.recommendations"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入处理建议"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  v-model="formData.remarks"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入备注信息"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 附件上传 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>附件上传</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="检测报告">
                <el-upload
                  class="upload-demo"
                  action="#"
                  :auto-upload="false"
                  :on-change="handleReportChange"
                  :file-list="reportFiles"
                >
                  <el-button type="primary">选择文件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      支持 jpg/png/pdf 文件，且不超过 10MB
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检测照片">
                <el-upload
                  class="upload-demo"
                  action="#"
                  :auto-upload="false"
                  :on-change="handlePhotoChange"
                  :file-list="photoFiles"
                  list-type="picture-card"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Plus, Delete } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'InspectionForm',
  components: {
    ArrowLeft,
    Plus,
    Delete
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const inspectionForm = ref(null)
    const submitLoading = ref(false)
    
    // 判断是否为编辑模式
    const isEdit = computed(() => {
      return !!route.params.id
    })
    
    // 表单数据
    const formData = reactive({
      id: null,
      inspectionCode: '',
      inspectionType: '',
      productId: null,
      batchNumber: '',
      supplierId: null,
      inspectionDate: '',
      inspector: '',
      inspectionLocation: '',
      testItems: [],
      totalTests: 0,
      passedTests: 0,
      failedTests: 0,
      passRate: '0',
      overallResult: '合格',
      status: 'processing',
      conclusion: '',
      recommendations: '',
      remarks: ''
    })
    
    // 表单验证规则
    const rules = {
      inspectionCode: [
        { required: true, message: '请输入检测编号', trigger: 'blur' }
      ],
      inspectionType: [
        { required: true, message: '请选择检测类型', trigger: 'change' }
      ],
      productId: [
        { required: true, message: '请选择商品', trigger: 'change' }
      ],
      batchNumber: [
        { required: true, message: '请输入生产批次', trigger: 'blur' }
      ],
      supplierId: [
        { required: true, message: '请选择供应商', trigger: 'change' }
      ],
      inspectionDate: [
        { required: true, message: '请选择检测日期', trigger: 'change' }
      ],
      inspector: [
        { required: true, message: '请输入检测员', trigger: 'blur' }
      ],
      overallResult: [
        { required: true, message: '请选择综合判定', trigger: 'change' }
      ]
    }
    
    // 模拟商品数据
    const products = ref([
      { id: 1, name: '有机苹果', code: 'P001' },
      { id: 2, name: '有机胡萝卜', code: 'P002' },
      { id: 3, name: '有机白菜', code: 'P003' },
      { id: 4, name: '有机土豆', code: 'P004' }
    ])
    
    // 模拟供应商数据
    const suppliers = ref([
      { id: 1, name: '绿色农场供应商' },
      { id: 2, name: '优质食品供应商' },
      { id: 3, name: '新鲜果蔬供应商' }
    ])
    
    // 文件列表
    const reportFiles = ref([])
    const photoFiles = ref([])
    
    // 加载检测报告详情（编辑模式）
    const loadInspectionDetail = async () => {
      if (!isEdit.value) return
      
      try {
        // 模拟API请求
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 模拟编辑数据
        Object.assign(formData, {
          id: route.params.id,
          inspectionCode: 'QC20240115001',
          inspectionType: 'routine',
          productId: 1,
          batchNumber: '20240115-001',
          supplierId: 1,
          inspectionDate: '2024-01-15',
          inspector: '王五',
          inspectionLocation: '质检中心',
          testItems: [
            {
              testItem: '农药残留',
              testMethod: 'GB/T 5009.199',
              testValue: '未检出',
              standard: '≤0.01mg/kg',
              unit: 'mg/kg',
              testResult: '合格'
            },
            {
              testItem: '重金属',
              testMethod: 'GB 5009.12',
              testValue: '0.005',
              standard: '≤0.1',
              unit: 'mg/kg',
              testResult: '合格'
            }
          ],
          overallResult: '合格',
          status: 'completed',
          conclusion: '该批次商品检测结果合格，符合国家标准要求。',
          recommendations: '建议正常销售，继续加强质量监控。',
          remarks: '检测过程严格按照标准执行，结果可靠。'
        })
        
        // 计算统计数据
        calculateStatistics()
      } catch (error) {
        console.error('加载检测报告详情失败:', error)
        ElMessage.error('加载检测报告详情失败')
      }
    }
    
    // 商品选择变化
    const handleProductChange = (productId) => {
      const product = products.value.find(p => p.id === productId)
      if (product) {
        formData.inspectionCode = `QC${new Date().toISOString().slice(0, 10).replace(/-/g, '')}001`
      }
    }
    
    // 添加检测项目
    const addTestItem = () => {
      formData.testItems.push({
        testItem: '',
        testMethod: '',
        testValue: '',
        standard: '',
        unit: '',
        testResult: '合格'
      })
    }
    
    // 删除检测项目
    const removeTestItem = (index) => {
      formData.testItems.splice(index, 1)
    }
    
    // 计算统计数据
    const calculateStatistics = () => {
      formData.totalTests = formData.testItems.length
      formData.passedTests = formData.testItems.filter(item => item.testResult === '合格').length
      formData.failedTests = formData.testItems.filter(item => item.testResult === '不合格').length
      formData.passRate = formData.totalTests > 0 ? ((formData.passedTests / formData.totalTests) * 100).toFixed(1) : '0'
    }
    
    // 监听检测项目变化
    watch(() => formData.testItems, () => {
      calculateStatistics()
    }, { deep: true })
    
    // 处理报告文件变化
    const handleReportChange = (file, fileList) => {
      reportFiles.value = fileList
    }
    
    // 处理照片文件变化
    const handlePhotoChange = (file, fileList) => {
      photoFiles.value = fileList
    }
    
    // 提交表单
    const handleSubmit = async () => {
      try {
        await inspectionForm.value.validate()
        submitLoading.value = true
        
        // 模拟提交请求
        await new Promise(resolve => setTimeout(resolve, 2000))
        
        ElMessage.success(isEdit.value ? '检测报告更新成功' : '检测报告添加成功')
        router.push('/quality/list')
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败，请检查输入信息')
      } finally {
        submitLoading.value = false
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }
    
    onMounted(() => {
      loadInspectionDetail()
    })
    
    return {
      isEdit,
      inspectionForm,
      formData,
      rules,
      products,
      suppliers,
      reportFiles,
      photoFiles,
      submitLoading,
      loadInspectionDetail,
      handleProductChange,
      addTestItem,
      removeTestItem,
      calculateStatistics,
      handleReportChange,
      handlePhotoChange,
      handleSubmit,
      goBack
    }
  }
})
</script>

<style scoped>
.inspection-form {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  color: #2563eb;
}

.form-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.test-item {
  border: 1px solid #e1e5e9;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  background: #f8f9fa;
}

.inspection-form-container {
  max-width: 1200px;
  margin: 0 auto;
}

.upload-demo {
  width: 100%;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-right {
    width: 100%;
    display: flex;
    gap: 10px;
  }
  
  .form-content {
    padding: 10px;
  }
  
  .test-item {
    padding: 10px;
  }
}
</style> 